package vip.youngboy.freejump.handler.task;

import com.google.common.collect.Maps;
import org.activiti.engine.ActivitiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import vip.youngboy.freejump.constant.TaskActionType;
import vip.youngboy.freejump.domain.FlowRequestParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
public class TaskHandler {

    protected Map<TaskActionType, TaskActionHandler> taskActionHandlerMap = new HashMap<>();


    @Autowired
    public void setTaskActionHandlers(List<TaskActionHandler> taskActionHandlers) {
        taskActionHandlerMap = Optional
                .ofNullable(taskActionHandlers)
                .map(
                        item -> item.stream().collect(
                                Collectors.toMap(action -> action.supportAction(), action -> action)
                        )).orElse(new HashMap<>());
    }


    /**
     * 处理流程
     *
     * @param flowRequestParam 处理请求对象
     * @return 处理结果
     */
    public Map<String, String> handleTask(FlowRequestParam flowRequestParam) {
        Map<String, String> result = Maps.newHashMap();
        String action = flowRequestParam.getAction();
        TaskActionType taskActionType = TaskActionType.fromKey(action);
        TaskActionHandler taskActionHandler = taskActionHandlerMap.get(taskActionType);
        if (taskActionHandler == null) {
            throw new ActivitiException("没有对应动作的处理器");
        }
        taskActionHandler.handleAction(flowRequestParam);
        result.put("msg", "success");
        result.put("code", "200");
        return result;
    }


}
